package com.ced.sip.system.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.system.biz.IDepartmentsBiz;
import com.ced.sip.system.biz.ISysMenuBiz;
import com.ced.sip.system.biz.ISysRoleBiz;
import com.ced.sip.system.biz.ISysRoleMenuRelaBiz;
import com.ced.sip.system.biz.ISysUserRoleRelaBiz;
import com.ced.sip.system.biz.IUsersBiz;
import com.ced.sip.system.entity.Departments;
import com.ced.sip.system.entity.SysMenu;
import com.ced.sip.system.entity.SysRole;
import com.ced.sip.system.entity.SysRoleMenuRela;
import com.ced.sip.system.entity.SysUserRoleRela;
import com.ced.sip.system.entity.Users;

public class SysMenuAction  extends BaseAction {

	private static final long serialVersionUID = 1L;	
	private ISysMenuBiz iSysMenuBiz;
	private ISysRoleBiz iSysRoleBiz;
	//部门
	private IDepartmentsBiz iDepartmentsBiz;
	private ISysRoleMenuRelaBiz iSysRoleMenuRelaBiz;
	private ISysUserRoleRelaBiz iSysUserRoleRelaBiz;
	private IUsersBiz iUsersBiz;
	
	Map<String, Object> map = new HashMap<String, Object>();
	/**
	 * 菜单页
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String viewMenuIndex() {
		
		return "initmenu" ;
	}
	
	/**
	 * 通过ajax方式获取菜单
	 * @return
	 * @throws BaseException 
	 * @throws IOException 
	 * @Action
	 */
	public String findMenuData() throws BaseException, IOException  {
		
		try{
			String code = this.getRequest().getParameter("id");
			if(StringUtil.isBlank(code)) code="999999";
			SysMenu menu = new SysMenu();
			menu.setPmenuCode(code);
			List<SysMenu> menulist = iSysMenuBiz.getSysMenuList(menu);

			JSONArray jsonArray = new JSONArray();
			for (SysMenu menul:menulist) {
				JSONObject subJsonObject = new JSONObject();
				subJsonObject.element("id", menul.getMenuCode());
				subJsonObject.element("pid", menul.getPmenuCode());
				subJsonObject.element("name",menul.getMenuName());
				
				if("0".equals(menul.getMenuFolderFlag()))
				{
					subJsonObject.element("isParent", true);
					
				}
				
				jsonArray.add(subJsonObject);
			}
			PrintWriter writer = getResponse().getWriter();  
			//System.out.println(jsonArray);
	        writer.print(jsonArray);  
	        writer.flush();  
	        writer.close(); 
		}catch(Exception e){
			log("通过ajax方式获取菜单错误！", e);
			throw new BaseException("通过ajax方式获取菜单错误！", e);
		}
		
		return null;
	}
	
	public String initSysMenu(){
		try{
			String pmenuCode = this.getRequest().getParameter("pmenuCode");
			String menuCode = this.getRequest().getParameter("menuCode");
			SysMenu pmenu = iSysMenuBiz.getSysMenuById(pmenuCode);
			SysMenu menu = iSysMenuBiz.getSysMenuById(menuCode);
			this.getRequest().setAttribute("pmenu", pmenu);
			this.getRequest().setAttribute("menu", menu);
			this.getRequest().setAttribute("menuCode", pmenuCode);
		}catch(Exception e){
			
		}
		return "init_addorupdate_menu";
	}
	
	public String initTwoSysMenu(){
		try{
			String menuCode = this.getRequest().getParameter("menuCode");
			SysMenu menu = iSysMenuBiz.getSysMenuById(menuCode);
			
			this.getRequest().setAttribute("pmenu", menu);
			//System.out.println(menu.getMenuName()+"------------");
		}catch(Exception e){
			
		}
		return "init_addTwoorupdate_menu";
	}
	
	/**
	 * 通过ajax方式获取菜单
	 * @return
	 * @throws BaseException 
	 * @throws IOException 
	 * @Action
	 */
	public String saveMenuData() throws BaseException, IOException  {
		boolean flag = false;
		String prm=this.getRequest().getParameter("prm");
		try{
			SysMenu menu = new SysMenu();
			String menuId = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("menuId"));
			String menuCode = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("menuCode"));
			String menuName = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("menuName"));
			String pmenuCode = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("pmenuCode"));
			String menuFolderFlag = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("menuFolderFlag"));
			String sortNo = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("sortNo"));
			String pathCode = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("pathCode"));
			String isActive = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("isActive"));
			String remark = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("remark"));
			String menuImg = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("menuImg"));
			//String tmpCode = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("tmpCode"));
			String menuLevel = StringUtil.convertBlankToEmptryBlank(this.getRequest().getParameter("menuLevel"));
			menu.setMenuId(menuId == "" ? 0 : Long.parseLong(menuId));
			menu.setMenuCode(menuCode);
			menu.setMenuName(menuName);
			menu.setPmenuCode(pmenuCode);
			menu.setMenuFolderFlag(menuFolderFlag);
			menu.setSortNo(sortNo);
			menu.setPathCode(pathCode);
			menu.setIsActive(isActive);
			menu.setMenuLevel(menuLevel);
			menu.setRemark(remark);
			menu.setWriteDate(DateUtil.getCurrentDateTime());
			menu.setWriter(UserRightInfoUtil.getUserName(this.getRequest()));
			menu.setMenuImg(menuImg);
			if("update".equals(prm)){
				iSysMenuBiz.updateSysMenu(menu);
			}else{
				iSysMenuBiz.saveSysMenu(menu);
			}
			flag = true;
		}catch(Exception e){
			log("通过ajax方式获取菜单错误！", e);
			throw new BaseException("通过ajax方式获取菜单错误！", e);
		}
		PrintWriter writer = this.getResponse().getWriter();  
        writer.print(flag);  
        writer.flush();  
        writer.close();
		
		return null;
	}

	/**
	 * 通过ajax方式获取菜单
	 * @return
	 * @throws BaseException 
	 * @throws IOException 
	 * @Action
	 */
	public String deleteMenu() throws BaseException, IOException  {
		//boolean flag = false;
		try{
			String menuCode = this.getRequest().getParameter("menuCode");
			SysMenu menu = iSysMenuBiz.getSysMenuById(menuCode);
			iSysMenuBiz.deleteSysMenu(menu);

			PrintWriter writer = this.getResponse().getWriter();  
			String message="删除成功";
			writer.print(message);  
	        writer.flush();  
	        writer.close();
		}catch(Exception e){
			log("通过ajax方式获取菜单错误！", e);
			throw new BaseException("通过ajax方式获取菜单错误！", e);
		}
		
       
		return null;
	}
	
	public String initRoles(){
		return "initroles";
	}

	public String findRoles(){
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			String roleName = this.getRequest().getParameter("roleName");
			SysRole role = new SysRole();
			if(!UserRightInfoUtil.ifSystemManagerRole(this.getRequest())) role.setComId(comId);
			if(StringUtil.isNotBlank(roleName)){
				role.setRoleName(roleName);
			}
			List<SysRole> srList=new ArrayList<SysRole>();
			List<Object[]> list=this.iSysRoleBiz.getSysRoleList( this.getRollPageDataTables(), role );
			for(Object[] obj:list){
				role=(SysRole)obj[0];
				role.setCompName((String)obj[1]);
				srList.add(role);
			}
			this.getPagejsonDataTables(srList);
		}catch(Exception e){
			
		}
		return null;
	}
	
	public String editRoles(){
		try{
			String roleId = this.getRequest().getParameter("roleId");
			if(StringUtil.isNotBlank(roleId)){
				SysRole role = iSysRoleBiz.getSysRole(Long.parseLong(roleId));
				this.getRequest().setAttribute("role", role);
			}
			this.getRequest().setAttribute("roleId", roleId);
		}catch(Exception e){
			
		}
		return "editroles";
	}
	
	public String saveRoles() throws IOException{
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			String roleId = StringUtil.convertBlankToEmptryBlank(this.getRequest()
					.getParameter("roleId"));
			String roleNo = StringUtil.convertBlankToEmptryBlank(this.getRequest()
					.getParameter("roleNo"));
			String roleName = StringUtil.convertBlankToEmptryBlank(this.getRequest()
					.getParameter("roleName"));
			String isActive = StringUtil.convertBlankToEmptryBlank(this.getRequest()
					.getParameter("isActive"));
			String roleDesc = StringUtil.convertBlankToEmptryBlank(this.getRequest()
					.getParameter("roleDesc"));
			
			SysRole sysRole = new SysRole();
			sysRole.setRoleId(roleId == "" ? 0 : Long.parseLong(roleId));
			sysRole.setRoleNo(roleNo);
			sysRole.setRoleName(roleName);
			sysRole.setWriter(UserRightInfoUtil.getChineseName(this.getRequest()));
			sysRole.setWriteDate(DateUtil.getCurrentDateTime());
			sysRole.setIsActive(isActive);
			sysRole.setRoleDesc(roleDesc);
			sysRole.setComId(comId);
			if(StringUtil.isNotBlank(roleId)){
				
				this.iSysRoleBiz.updateSysRole(sysRole);
				
				this.getRequest().setAttribute("message", "修改成功");
			}else{
				
				this.iSysRoleBiz.saveSysRole(sysRole);
				this.getRequest().setAttribute("message", "新增成功");
			}
			
		}catch(Exception e){
			
		}
		
        return "editroles";
	}
	
	public void deleteSysRole() throws IOException{
		boolean flag = false;
		try{
			String roles = this.getRequest().getParameter("roles");
			iSysRoleBiz.deleteSysRole(roles.split(","));
			flag = true;
		}catch(Exception e){
			
		}
		
		PrintWriter writer = this.getResponse().getWriter();  
        writer.println(flag);  
        
	}
	/**
	 * 保存角色权限
	 * @return
	 * @throws IOException
	 * @throws BaseException
	 */
	public String saveAuthorizeSysRole() throws IOException, BaseException{
		boolean flag = false;
		try{
			String roleId = this.getRequest().getParameter("roleId");
			
			SysRoleMenuRela srmr = new SysRoleMenuRela();
			srmr.setRoleId(roleId);
			List<SysRoleMenuRela> roleLst = iSysRoleMenuRelaBiz.getSysRoleMenuRelaList(srmr);
			if(roleLst.size() > 0){
				for(SysRoleMenuRela rela : roleLst){
					//删除角色权限
					iSysRoleMenuRelaBiz.deleteSysRoleMenuRela(rela.getId().toString());
				}
			}
			String menus = this.getRequest().getParameter("menus");
			String[] menuItems = menus.split(",");
			for(int i=0; i<menuItems.length; i++){
				String[] menuItem = menuItems[i].split("@");
				SysRoleMenuRela rela = new SysRoleMenuRela();
				rela.setMenuCode(menuItem[0]);
				rela.setMenuId(menuItem[1]);
				rela.setRoleId(roleId);
				rela.setWriter(UserRightInfoUtil.getUserName(this.getRequest()));
				rela.setWriteDate(DateUtil.getCurrentDateTime());
				iSysRoleMenuRelaBiz.saveSysRoleMenuRela(rela);
			}
			flag = true;
		}catch(Exception e){
			log("角色授权失败！", e);
			throw new BaseException("角色授权失败！", e);
		}
		PrintWriter writer = this.getResponse().getWriter();  
        writer.print(flag); 
        return null;
	}

	public String selectMenu(){
		String roleId = this.getRequest().getParameter("roleId");
		this.getRequest().setAttribute("roleId", roleId);
		
		return "selectMenu";
	}
	
	/**
	 * 通过ajax方式获取菜单
	 * @return
	 * @throws BaseException 
	 * @throws IOException 
	 * @Action
	 */
	public String selectMenuData() throws BaseException, IOException  {
		
		try{
			    Long comId=UserRightInfoUtil.getComId(getRequest());
			    Long userId=UserRightInfoUtil.getUserId(this.getRequest());
			    String roleId = this.getRequest().getParameter("roleId");
			    //如果是超级管理员，则可以分配所有的菜单，否则只能分配自己权限下的菜单信息
			    List<SysMenu> menulist=null;
			    if(comId.equals(0L)){
				  SysMenu menu = new SysMenu();
				  menu.setIsActive("1");
				//menu.setPmenuCode(code);
				  menulist = iSysMenuBiz.getSysMenuList(menu);
			    }else{
			      menulist= iSysMenuBiz.getTreeSysMenuListByUserId(userId+"");
			    }
				
				SysRoleMenuRela roleMenuRela=new SysRoleMenuRela();
				roleMenuRela.setRoleId(roleId);
				List<SysRoleMenuRela> roleMenulist=iSysRoleMenuRelaBiz.getSysRoleMenuRelaList(roleMenuRela);
				
				JSONArray jsonArray = new JSONArray();
				JSONObject subJsonObject=null;
				for (SysMenu menul:menulist) {
					    subJsonObject = new JSONObject();
						if("0".equals(menul.getPmenuCode()))
						{
							subJsonObject.element("open", true);
						}
					
					subJsonObject.element("id", menul.getMenuCode());
					subJsonObject.element("pid", menul.getPmenuCode());
					subJsonObject.element("name",menul.getMenuName());
					subJsonObject.element("code", menul.getMenuId());
					
					if("0".equals(menul.getMenuFolderFlag()))
					{
						//subJsonObject.element("isParent", true);
					}
					String id=menul.getMenuId().toString();
					for (SysRoleMenuRela roleMenu:roleMenulist) {
						
						if(id.equals(roleMenu.getMenuId()))
						{
							subJsonObject.element("checked", true);
						}
						if(id.equals(roleMenu.getMenuId()) && "0".equals(menul.getMenuFolderFlag()))
						{
							subJsonObject.element("open", true);
						}
					}
					
					
					jsonArray.add(subJsonObject);
				}
			//}
			PrintWriter writer = getResponse().getWriter();  
			//System.out.println(jsonArray);
	        writer.print(jsonArray);  
	        writer.flush();  
	        writer.close(); 
	        
		}catch(Exception e){
			log("通过ajax方式获取菜单错误！", e);
			throw new BaseException("通过ajax方式获取菜单错误！", e);
		}
		return null;
	}
	/**
	 * 根据权限id获取该权限的用户id
	 * @return
	 * @throws BaseException
	 * @throws IOException 
	 */
	public String getUsersByroleId() throws BaseException, IOException{
		String users="";
		try{
			Long roleId = Long.parseLong(this.getRequest().getParameter("roleId"));
			SysUserRoleRela sysUserRoleRela=new SysUserRoleRela();
			sysUserRoleRela.setRoleId(roleId);
			
			List<SysUserRoleRela> roleLst = iSysUserRoleRelaBiz.getSysUserRoleRelaList(sysUserRoleRela);
			if(roleLst.size() > 0){
				for(SysUserRoleRela rela : roleLst){
					users+=rela.getUserId()+",";
				}
			}
		}catch(Exception e){
			log("通过ajax方式获取用户错误！", e);
			throw new BaseException("通过ajax方式获取用户错误！", e);
		}
		PrintWriter writer = this.getResponse().getWriter();  
        writer.print(users);  
        writer.flush();  
        writer.close();
        
		return null;
	}
	public String authorizeByUser(){
		String roles = this.getRequest().getParameter("roles");
		this.getRequest().setAttribute("roles", roles);
		//选择流程节点审批人
		String param = this.getRequest().getParameter("param");
		this.getRequest().setAttribute("param", param);
		if(param.matches("[0-9]+")){
			return "processNodebyuser";
		}else {
			return "surrogatebyuser";
		}
		
	}	
	/**
	 * 批量保存用户授予的角色
	 * @return
	 * @throws IOException
	 * @throws BaseException
	 */
	public String saveAuthorizeByAllUsers_role() throws IOException, BaseException{
		PrintWriter writer = this.getResponse().getWriter();
		try{
			Long roleId=Long.parseLong(this.getRequest().getParameter("roleId"));
			String ids = this.getRequest().getParameter("ids");
			
			SysUserRoleRela srmr = new SysUserRoleRela();
			srmr.setRoleId(roleId);
			List<SysUserRoleRela> roleLst = iSysUserRoleRelaBiz.getSysUserRoleRelaList(srmr);
			for(SysUserRoleRela rela : roleLst){
				iSysUserRoleRelaBiz.deleteSysUserRoleRela(rela.getRelaId().toString());
			}
			
			
			String[] userId=ids.split(",");
 			for(int i=0;i<userId.length;i++){
 				SysUserRoleRela rela = new SysUserRoleRela();
				rela.setRoleId(roleId);
				rela.setUserId(Long.parseLong(userId[i]));
				rela.setWriter(UserRightInfoUtil.getUserName(this.getRequest()));
				rela.setWriteDate(DateUtil.getCurrentDateTime());
				iSysUserRoleRelaBiz.saveSysUserRoleRela(rela);
			}
			
 			  
 	        writer.print("授权成功"); 
			
			
		}catch(Exception e){
			log("保存用户授予的角色失败！", e);
			writer.print("授权失败");
			throw new BaseException("保存用户授予的角色失败！", e);
		}
		
        return null;
	}
	
	public String getDeptTreeData() throws IOException{
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			//获取部门所以信息
			Departments departments=new Departments();
			departments.setComId(comId);
			List<Departments> deptList =this.iDepartmentsBiz.getDepartmentsList(departments);
			
			
			JSONArray jsonArray = new JSONArray();
			for (Departments dept:deptList) {
				JSONObject subJsonObject = new JSONObject();
				subJsonObject.element("id", dept.getDepId());
				subJsonObject.element("pid", dept.getParentDeptId());
				subJsonObject.element("name",dept.getDeptName());
				
				if("1".equals(dept.getDepId()+""))
				{
					subJsonObject.element("open", true);
				}
				
				jsonArray.add(subJsonObject);
			}
			PrintWriter writer = getResponse().getWriter();  
	        writer.print(jsonArray);  
	        writer.flush();  
	        writer.close(); 
	        
		}catch(Exception e){
			
		}
        return null;
	}
	
	public String findUserByDeptId() throws BaseException{
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			String userChinesename =  this.getRequest().getParameter("userChinesename");
			String depId = this.getRequest().getParameter("depId");
			Users user = new Users();
			user.setComId(comId);
			if(!StringUtil.isNotBlank(userChinesename)){
				user.setDepId(Long.parseLong(depId));
			}
			user.setUserChinesename(userChinesename);
			
			this.setListValue( this.iUsersBiz.getUsersListRight(this.getRollPageDataTables(), user)) ;
			this.getPagejsonDataTables(this.getListValue());
			
		} catch (Exception e) {
			log.error("查看角色权限信息列表错误！", e);
		}
		return null;
	}
	public ISysMenuBiz getiSysMenuBiz() {
		return iSysMenuBiz;
	}
	public void setiSysMenuBiz(ISysMenuBiz iSysMenuBiz) {
		this.iSysMenuBiz = iSysMenuBiz;
	}
	public ISysRoleBiz getiSysRoleBiz() {
		return iSysRoleBiz;
	}
	public void setiSysRoleBiz(ISysRoleBiz iSysRoleBiz) {
		this.iSysRoleBiz = iSysRoleBiz;
	}
	public ISysRoleMenuRelaBiz getiSysRoleMenuRelaBiz() {
		return iSysRoleMenuRelaBiz;
	}
	public void setiSysRoleMenuRelaBiz(ISysRoleMenuRelaBiz iSysRoleMenuRelaBiz) {
		this.iSysRoleMenuRelaBiz = iSysRoleMenuRelaBiz;
	}
	public ISysUserRoleRelaBiz getiSysUserRoleRelaBiz() {
		return iSysUserRoleRelaBiz;
	}
	public void setiSysUserRoleRelaBiz(ISysUserRoleRelaBiz iSysUserRoleRelaBiz) {
		this.iSysUserRoleRelaBiz = iSysUserRoleRelaBiz;
	}

	public IUsersBiz getiUsersBiz() {
		return iUsersBiz;
	}

	public void setiUsersBiz(IUsersBiz iUsersBiz) {
		this.iUsersBiz = iUsersBiz;
	}

	public IDepartmentsBiz getiDepartmentsBiz() {
		return iDepartmentsBiz;
	}

	public void setiDepartmentsBiz(IDepartmentsBiz iDepartmentsBiz) {
		this.iDepartmentsBiz = iDepartmentsBiz;
	}
	
}
